# 异常找不到这个MySQL模块：按照MySQL-connector之后要在编辑器里面install一下
# 具体步骤： https://blog.csdn.net/virusss/article/details/103164058

import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="123456",
    database="py-db"
)

mycursor = mydb.cursor()
# 创建一个数据库：
# mycursor.execute("CREATE DATABASE runoob_db")
mycursor.execute("SHOW DATABASES")
# for x in mycursor:
    # print(x)
# mycursor.execute("CREATE TABLE sites (name VARCHAR(255), url VARCHAR(255))")
# sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
# val = ("RUNOOB", "https://www.runoob.com")
# mycursor.execute(sql, val)
# 批量插入
# 批量插入使用 executemany() 方法，该方法的第二个参数是一个元组列表，包含了我们要插入的数据：

# val = [
#   ('Google', 'https://www.google.com'),
#   ('Github', 'https://www.github.com'),
#   ('Taobao', 'https://www.taobao.com'),
#   ('stackoverflow', 'https://www.stackoverflow.com/')
# ]
# mycursor.executemany(sql, val)

mycursor.execute("SELECT * FROM sites")


myresult = mycursor.fetchall()  # fetchall() 获取所有记录
for x in myresult:
  print(x)
# 读取一条数据：mycursor.fetchone()
#插入之后获取ID：mycursor.lastrowid

mydb.commit()  # 数据表内容有更新，必须使用到该语句